package com.bestow.dox4j.utils;

import org.docx4j.openpackaging.exceptions.InvalidFormatException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.Part;
import org.docx4j.openpackaging.parts.PartName;
import org.docx4j.openpackaging.parts.Parts;
import org.docx4j.wml.*;
import org.springframework.util.StringUtils;

import java.math.BigInteger;
import java.util.List;

public class Docx4jUtils {

    public Docx4jUtils() {}

    public static Part getNamedPart(WordprocessingMLPackage workPackage, String partName) {
        Parts parts = workPackage.getParts();
        if (parts != null) {
            Part part = null;

            try {
                part = parts.get(new PartName(partName));
                return part;
            } catch (InvalidFormatException var5) {
                throw new RuntimeException(partName + " is not valid format.");
            }
        } else {
            return null;
        }
    }

    public static List<Object> getPartContent(Part part) {
        return part instanceof ContentAccessor ? ((ContentAccessor)part).getContent() : null;
    }

    public static R makeRWithContent(String value, String fontFamily, String fontSize, String underLine, String bold) {
        R run = new R();
        Text t = new Text();
        RPr rPr = new RPr();
        RFonts RFonts = new RFonts();
        RFonts.setHint(STHint.EAST_ASIA);
        RFonts.setEastAsia(fontFamily);
        RFonts.setAscii(fontFamily);
        RFonts.setHAnsi(fontFamily);
        if (!StringUtils.isEmpty(fontSize)) {
            HpsMeasure sz = new HpsMeasure();
            sz.setVal(new BigInteger(fontSize));
            rPr.setSz(sz);
            rPr.setSzCs(sz);
        }

        if (!StringUtils.isEmpty(underLine)) {
            U U = new U();
            rPr.setU(U);
            if ("SINGLE".equalsIgnoreCase(underLine)) {
                U.setVal(UnderlineEnumeration.SINGLE);
            } else {
                U.setVal(UnderlineEnumeration.DOUBLE);
            }
        }

        if ("Y".equalsIgnoreCase(bold)) {
            BooleanDefaultTrue b = new BooleanDefaultTrue();
            b.setVal(true);
            rPr.setB(b);
        }

        if ("R".equals(value) && "Wingdings 2".equals(fontFamily)) {
            R.Sym sym = new R.Sym();
            sym.setChar("F052");
            sym.setFont(fontFamily);
            run.setRPr(rPr);
            run.getContent().add(sym);
        } else {
            rPr.setRFonts(RFonts);
            run.getContent().add(t);
            run.setRPr(rPr);
            t.setValue(value);
        }

        return run;
    }
}
